package com.k8.exchange;

import com.k8.rpc.invoke.invocation.Invocation;
import com.k8.rpc.result.Result;
import com.k8.rpc.serialize.Serializer;
import com.key.w8.http1.entity.HttpRequest;
import com.key.w8.http1.entity.HttpResponse;
import com.key.w8.http1.handler.codec.ByteBufAllocatorHolder;
import com.key.w8.http1.handler.codec.HttpObjectClientResolver;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.*;

import static com.k8.exchange.constants.HeaderConstants.INVOCATION_KEY;
import static com.k8.exchange.constants.HeaderConstants.SERIALIZER_KEY;

/**
 * @Author: k8
 * @CreateTime: 2025-08-15
 * @Version: 1.0
 */
public class SerializeClientResolver implements HttpObjectClientResolver {
    private Serializer serializer;

    public SerializeClientResolver(Serializer serializer) {
        this.serializer = serializer;
    }

    @Override
    public boolean canResolverRequestOut(HttpRequest httpRequest) {
        if (httpRequest.complexObject() != null && httpRequest.complexObject() instanceof Invocation) return true;
        return false;
    }

    @Override
    public FullHttpRequest resolverRequestOut(HttpRequest httpRequest, ByteBufAllocatorHolder allocatorHolder) {
        ByteBuf buffer = allocatorHolder.alloc().buffer();
        Invocation invocation = (Invocation) httpRequest.complexObject();
        ByteBuf byteBuf = serializer.encode(invocation, buffer);
        httpRequest.headers().add(SERIALIZER_KEY, serializer.serializerName());
        httpRequest.headers().add(INVOCATION_KEY, invocation.getInvocationKey());
        DefaultFullHttpRequest fRequest = new DefaultFullHttpRequest(httpRequest.version(), httpRequest.method(), httpRequest.uri(), byteBuf, httpRequest.headers(), EmptyHttpHeaders.INSTANCE);
        fRequest.headers()
                .set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());
        return fRequest;
    }

    @Override
    public boolean canResolverResponseIn(FullHttpResponse fullHttpResponse) {
        return fullHttpResponse.headers().contains("k8Protocol");
    }

    @Override
    public HttpResponse resolverResponseIn(FullHttpResponse fullHttpResponse) {
        ByteBuf content = fullHttpResponse.content();
        Result result = serializer.decode(content, Result.class);
        HttpResponse response = new HttpResponse(fullHttpResponse.headers(), fullHttpResponse.protocolVersion(), fullHttpResponse.status());
        response.setComplexObject(result);
        return response;
    }

}
